'''
查询参数
'''
from typing import Union, List

from fastapi import APIRouter, Query
from pydantic.v1 import Required

router = APIRouter()

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


@router.get("/query/items", tags=["查询参数"])
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip:skip + limit]


# 可选参数
#   q: Union[str, None] :设置参数可选，要么是str 类型 ，要么是none
#   也可以写成 q: str = None
#   Query: 是数据校验
#       regex : 正则校验
@router.get("/query/items/{item_id}", tags=["查询参数"])
async def read_item(item_id: str,
                    q: Union[str, None] = Query(default=None, max_length=50, min_length=3, regex="^fixedquery$")):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}


#   ... : 设置参数必填
@router.get("/query/items_2/{item_id}", tags=["查询参数"])
async def read_item2(item_id: str,
                     q: str = Query(default=..., max_length=50, min_length=3)):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}


# 不设置default值，则默认为参数是必须填的
@router.get("/query/items_3/{item_id}", tags=["查询参数"])
async def read_item2(item_id: str, q: str = Query(max_length=50, min_length=3)):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}


@router.get("/query/items_4/{item_id}", tags=["查询参数"])
async def read_item2(item_id: str, q: str = Query(default=Required, max_length=50, min_length=3)):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}


@router.get("/query/items_5/{item_id}", tags=["查询参数"])
async def read_item_2(item_id: str, q: Union[str, None] = None, short: bool = False):
    item = {"item_id": item_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item


# 参数校验
@router.get("/query/get_items/", tags=["查询参数"])
async def get_items(query: Union[str, None] = Query(default=None, max_length=5)):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if query:
        results.update({"query": query})
    return results


#  List 作为参数
#  要声明类型为 list 的查询参数，必须显式地使用 Query，否则该参数将被解释为请求体。
@router.post("/query/inset_items/", tags=["查询参数"])
async def read_items(q: Union[List[str], None] = Query(default=None)):
    query_items = {"q": q}
    return query_items


@router.post("/query/inset_items_2/", tags=["查询参数"])
async def read_items(q: Union[List[str], None] = Query(default=["foo", "bar"])):
    query_items = {"q": q}
    return query_items


#  使用基本类型list
#  alias :参数别名
@router.post("/query/inset_items_3/", tags=["查询参数"])
async def read_items(q: list = Query(default=["foo", "bar"], title="是一个list数据",
                                     alias="query",
                                     description="集合数据")):
    query_items = {"q": q}
    return query_items
